package com.lin.utils;

import com.tencent.SpeechClient;
import com.tencent.core.model.GlobalConfig;
import com.tencent.core.utils.ByteUtils;
import com.tencent.tts.model.*;
import com.tencent.tts.service.SpeechSynthesisListener;
import com.tencent.tts.service.SpeechSynthesizer;
import com.tencent.tts.service.SpeechSynthesisListener;
import com.tencent.tts.utils.OpusUtils;
import com.tencent.tts.utils.PcmUtils;
import com.tencent.tts.utils.Ttsutils;
/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/5/1 18:30
 * @Description
 */


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 语音合成 example
 */
public class TTSUtil {


    private static String codec = "pcm";
    private static int sampleRate = 16000;


    private static byte[] datas = new byte[0];


    /**
     * 语音合成
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        //从配置文件读取密钥
//        Properties props = new Properties();
////        props.load(Files.newInputStream(Paths.get("../../config.properties")));
//        String appId = props.getProperty("appId");
//        String secretId = props.getProperty("secretId");
//        String secretKey = props.getProperty("secretKey");
        String appId = "1307962242";
        String secretId = "AKIDvgCTVIrBG6hmcDZfW8VcWCdojPp0wd4G";
        String secretKey = "znNioeHgqkPoytZ0B7pHUSAcpnVyB9sN";
        //创建SpeechSynthesizerClient实例，目前是单例
        SpeechClient client = SpeechClient.newInstance(appId, secretId, secretKey);
        //初始化SpeechSynthesizerRequest，SpeechSynthesizerRequest包含请求参数
        SpeechSynthesisRequest request = SpeechSynthesisRequest.initialize();
        request.setCodec(codec);
        //request.setSampleRate(sampleRate);
        //request.setVolume(10);
        //request.setSpeed(2f);
        request.setVoiceType(101007);
        //使用客户端client创建语音合成实例
        SpeechSynthesizer speechSynthesizer = client.newSpeechSynthesizer(request, new MySpeechSynthesizerListener());
        //执行语音合成
        String ttsText = "腾讯云语音合成测试";
        speechSynthesizer.synthesis(ttsText);
    }


    public static byte[] init(String text) {
        String appId = "1307962242";
        String secretId = "AKIDvgCTVIrBG6hmcDZfW8VcWCdojPp0wd4G";
        String secretKey = "znNioeHgqkPoytZ0B7pHUSAcpnVyB9sN";
        //创建SpeechSynthesizerClient实例，目前是单例
        SpeechClient client = SpeechClient.newInstance(appId, secretId, secretKey);
        //初始化SpeechSynthesizerRequest，SpeechSynthesizerRequest包含请求参数
        SpeechSynthesisRequest request = SpeechSynthesisRequest.initialize();
        request.setCodec(codec);
        //request.setSampleRate(sampleRate);
        //request.setVolume(10);
        //request.setSpeed(2f);
        request.setVoiceType(101016);
        //使用客户端client创建语音合成实例
        SpeechSynthesizer speechSynthesizer = client.newSpeechSynthesizer(request, new MySpeechSynthesizerListener());
        //执行语音合成
        speechSynthesizer.synthesis(text);
        return datas;
    }

    public static class MySpeechSynthesizerListener extends SpeechSynthesisListener {


        private AtomicInteger sessionId = new AtomicInteger(0);


        @Override
        public void onComplete(SpeechSynthesisResponse response) {
            System.out.println("onComplete");
            if (response.getSuccess()) {
                //根据具体的业务选择逻辑处理
//                Ttsutils.saveResponseToFile(response.getAudio(),"./111.mp3");
                if ("pcm".equals(codec)) {
                    int rspLen = response.getAudio().length;
                    byte[] wav = new byte[44 + rspLen];
                    int bitNum = sampleRate == 16000 ? 16 : 8;
                    PcmUtils.Pcm2WavBytes(response.getAudio(), wav, sampleRate, 1, bitNum);
                    //pcm 转 wav
                    datas = wav;
//                    Ttsutils.responsePcm2Wav(sampleRate, response.getAudio(), response.getSessionId());
                }
                if ("opus".equals(codec)) {
                    //opus
                    System.out.println("OPUS:" + response.getSessionId() + " length:" + response.getAudio().length);
                }
//                datas = response.getAudio();

            }
            System.out.println("结束：" + response.getSuccess() + " " + response.getCode()
                    + " " + response.getMessage() + " " + response.getEnd());
        }


        //语音合成的语音二进制数据
        @Override
        public void onMessage(byte[] data) {
            //System.out.println("onMessage:" + data.length);
            // Your own logic.
            System.out.println("onMessage length:" + data.length);
            sessionId.incrementAndGet();
        }


        @Override
        public void onFail(SpeechSynthesisResponse response) {
            System.out.println("onFail"+response.getMessage());
        }
    }
}

